package com.itcast.reflect;

import com.itcast.domain.Person;

import java.lang.reflect.Field;

public class ReflectDemo2 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 1.获取 class 对象
        Class<Person> personClass = Person.class;

        // 2.获取成员变量
        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("--------");

        Field a = personClass.getField("a");
        // 获取成员变量 a 的值
        Person p = new Person();
        Object o = a.get(p);
        System.out.println(o);
        // 设置 a 的值
        a.set(p, "张三");
        System.out.println(p);

        System.out.println("=========");

        // 获取所有的成员变量
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }
        System.out.println("--------");

        Field d = personClass.getDeclaredField("d");
        // 忽略安全访问检测
        d.setAccessible(true); // 暴力反射
        Object o1 = d.get(p);
        System.out.println(o1);
        d.set(p, "王武");
        System.out.println(p);

    }
}
